<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>商品信息管理</title>
    <link rel="stylesheet" href="plugins/layui/css/layui.css" media="all" />
    <link rel="stylesheet" href="css/comments.css" media="all">
    <style>
        .layui-form-label{
            width: 120px;
        }
        @media screen and (max-width: 450px){
            .layui-form-item .layui-input-inline {
                margin-left: 150px;
            }
        }
        #tableForm{
            padding: 10px 20px;
            display: none;

        }
        #my_iframe{
            width: 100%;
            border: 0;
            height: 100%;
            display: none;
        }
    </style>
</head>
<body>
    <div class="maincontainer">
        <div class="layui-card">
            <div class="layui-card-header layuiadmin-card-header-auto">
                <form id="queryForm" class="layui-form" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">商品名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="productName" autocomplete="off" class="layui-input" placeholder="商品名称" maxlength="20">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">供应商名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="supplierName" autocomplete="off" class="layui-input" placeholder="供应商名称" maxlength="20">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">商品类别</label>
                            <div class="layui-input-inline">
                                <!-- <select name="productCategoryName" lay-search>
                                    <option value=""></option>
                                </select>  -->
                                <input type="text" name="categoryId" autocomplete="off" id="tree" lay-filter="tree" class="layui-input">
                                <!-- <input type="text" name="productCategoryName" autocomplete="off" class="layui-input" placeholder="商品类别" maxlength="20"> -->
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">审核状态</label>
                            <div class="layui-input-inline">
                                <select name="reviewStatus" lay-filter="reviewStatus">
                                    <option value=""></option>
                                    <option value="0">待审核</option>
                                    <option value="1">审核通过</option>
                                    <option value="2">审核不通过</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">检测报告是否过期</label>
                            <div class="layui-input-inline">
                                <select name="annexExpiredStatus" lay-filter="annexExpiredStatus">
                                    <option value=""></option>
                                    <option value="1">已过期</option>
                                    <option value="0">未过期</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">商品状态</label>
                            <div class="layui-input-inline">
                                <select name="shelfStatus" lay-filter="shelfStatus">
                                    <option value=""></option>
                                    <option value="1">上架</option>
                                    <option value="0">下架</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="button" class="layui-btn"  lay-submit lay-filter="searchBth">查询</button>
                            <button type="reset" class="layui-btn layui-btn-primary reReset" onclick="javascript:onReset()">重置</button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="layui-card-body">
                <table class="layui-hide" id="selectTable" lay-filter="selectTable"></table>
            </div>
        </div>

        <div id="tableForm">
            <table class="layui-hide" id="canteenTable" lay-filter="canteenTable"></table>
        </div>
    </div>
    <!-- <iframe id="my_iframe" src="" ></iframe> -->
</body>
<script type="text/html" id="state">
    <!-- 状态 -->
	<input type="checkbox" name="publicStatus" value="{{d.productId}}" lay-skin="switch" lay-filter="statusDemo" lay-text="是|否" {{ d.publicStatus==
	       1 ? 'checked' : '' }}>
</script>
<script type="text/html" id="toolbarDemo">
	<div class="layui-btn-container toolbarDemo">
		<button class="layui-btn layui-btn-sm" lay-event="change">批量审核同意</button>
		<button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="export">导出</button>
	</div>
</script>
<script type="text/javascript" src="plugins/layui/layui.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
    layui.config({
        base: 'plugins/layui/modules/',
    }).use(['http', 'table', 'form', 'treeSelect'], function() {
        var http = layui.http,
            table = layui.table,
            form = layui.form,
            treeSelect = layui.treeSelect;
        var excelList,currPage = 1,limit
        var canteenIdSet = [] // 批量审核商品id集合
        var canteenIdSetList = [] // 选中商品
		
        // 重置
        window.onReset = function() {
            treeSelect.revokeNode('tree', function(d){});
        }

        $('.reReset').click();
        
        var search = sessionStorage.getItem('xi-can-management-productMSearch')
        if(search){
            search = JSON.parse(search)
            currPage = search.page
            limit = search.limit
            
            $('input[name=productName]').val(search.productName)
            $('input[name=supplierName]').val(search.supplierName)
            $('select[name=reviewStatus]').val(search.reviewStatus)
            $('select[name=annexExpiredStatus]').val(search.annexExpiredStatus)
            $('select[name=shelfStatus]').val(search.shelfStatus)
        }

        // 分类查询
        // getCategory()
        // function getCategory() {
        //     http.get('admin/product/category/listAllCategory',{},function(res){
        //         if(res.code == 200){
        //             var html = '<option value="">请选择商品类别</option>';
        //             var data = res.data;
        //             for (var i = 0; i < data.length; i++) {
        //                 html += '<option value="' + data[i].categoryName + '">' + data[i].categoryName + '</option>'
        //             }
        //             $('select[name=productCategoryName]').html(html);
        //             form.render('select');
        //         }else{
        //             layer.msg(res.msg)
        //         }
        //     })
        // }
        getCategory()
        function getCategory() {
            var authentication = localStorage.getItem('xi-can-management-authentication')
            treeSelect.render({
                // 选择器
                elem: '#tree',
                // 数据
                data: TUrl + 'admin/product/category/listAllTree',
                // 异步加载方式：get/post，默认get
                type: 'get',
                headers: {
                    authentication: authentication
                },
                // 占位符
                placeholder: '商品类别',
                // 是否开启搜索功能：true/false，默认false
                search: true,
                style: {
                    folder: {
                        enable: false
                    },
                    line: {
                        enable: true
                    }
                },
                // 点击回调
                click: function(d){
                    // // console.log(d);
                },
                // 加载完成后的回调函数
                success: function (d) {
                    // // console.log(d);
                    if(search){
                        if(search.categoryId)
                            treeSelect.checkNode('tree', search.categoryId);
                        // $('input[name=categoryId]').val(search.categoryId)
                    }
                }
            });
        }

        var selectTable;
        selectTable = http.table({
            elem: '#selectTable',
            url: 'admin/product/listPage',
            method: 'get',
            id: 'selectTable',
            toolbar: '#toolbarDemo',
            where: {
                reviewStatus:  $('select[name=reviewStatus]').val(),
                annexExpiredStatus: $('select[name=annexExpiredStatus]').val(),
                shelfStatus: $('select[name=shelfStatus]').val(),
                productName: $('input[name=productName]').val(),
                supplierName: $('input[name=supplierName]').val(),
                categoryId: $('input[name=categoryId]').val()||(search?search.categoryId:''),
            },
            page: {
                curr: currPage,
                limit: limit
            },
            done: function(res, curr, count){
                excelList = res.data;
                currPage = curr
                limit = selectTable.config.limit
                getSearchVal() // 存储搜索条件  
                var isAll = []
                
                res.data.forEach(function(value, key) {
                    //这里必须选择点击方法，不知为何添加layui-form-checked class属性会造成二次点击（即下次点击必须点击两下才能生效）bug，
                    //所有类似的手动修改class貌似都会造成二次效果
                    if(canteenIdSet.indexOf(value.productId)!==-1){
                        value["LAY_CHECKED"]='true';
                        $(".layui-table tr[data-index="+key+"] input[type='checkbox']").prop('checked',true);
                        $(".layui-table tr[data-index="+key+"] input[type='checkbox']").next().addClass('layui-form-checked')
                    }
                    if(value.reviewStatus != 0){
                        $(".layui-table tr[data-index="+key+"] input[type='checkbox']").prop('disabled',true);
                        $(".layui-table tr[data-index="+key+"] input[type='checkbox']").next().addClass('layui-btn-disabled')
                    }else{
                        isAll.push(value)
                    }
                })
                var checkStatus = table.checkStatus('selectTable');
                if(checkStatus.data.length != 0 && checkStatus.data.length == isAll.length){ // 是否全选
                    $(' .layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                    $('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
                }
                // $(".layui-table-header th[data-field='0'] .layui-form-checkbox").hide()
			},
            cols: [[
                {type:'checkbox',fixed: 'left'},
                {title:'序号',type:'numbers',fixed: 'left'}
                ,{field:'mainImage', title: '商品图片', align : 'center',event: 'imgclick',
                    templet: function (d) {
                        return '<div ><img src="'+TUrl+d.mainImage+'" alt="" width="50px" height="30px"></div>'
                    }
                }
                ,{field:'productName', title: '商品名称', align : 'center',width: 170,
                    templet: function(d){
                        var html = ''
                        html += '<a class="buttoncolor" lay-event="detail" >'+d.productName+'</a>'
                        return html
                    }
                }
                ,{field:'supplierName', title: '供应商名称', align : 'center'}
                ,{field:'categoryName', title: '商品类别', align : 'center',width: 120,}
                ,{field:'unitName', title: '单位', align : 'center'}
                ,{field:'priceRange', title: '价格', align : 'center'}
                ,{field:'sortNumber', title: '排序', align : 'center'}
                ,{field:'shelfStatus', title: '商品状态', align : 'center',
					templet: function (d) {
						return d.shelfStatus==1?'上架':'下架';
                    }
                }
                ,{field:'reviewStatus', title: '审核状态', align : 'center',
					templet: function (d) {
						return d.reviewStatus==0?'<span style="color:#0066FF">待审核</span>':(d.reviewStatus==1?'<span style="color:#000000">审核通过</span>':'<span style="color: #FF0000">审核不通过</span>');
                    }
                }
                ,{field:'reportDueTime', title: '检测报告到期时间', align : 'center',width: 170,
					templet: function (d) {
						return d.reportDueTime?d.reportDueTime.split(' ')[0]:'';
                    }
                }
				,{field:'city', title: '是否公示', align : 'center', templet: "#state"}
                ,{field:'', title: '操作', align : 'center',fixed: 'right',width: 120,
                    templet: function (d) {
                        var html = '';
                        if(d.reviewStatus==0){
                            html += '<button type="button" class="layui-btn layui-btn-primary layui-btn-xs" lay-event="check" >审核</button>'
                        }else if(d.reviewStatus==1){
                            if(d.shelfStatus==0){
                                // html += '<button type="button" class="layui-btn layui-btn-primary layui-btn-xs" lay-event="up" >上架</button>'
                            }else{
                                html += '<button type="button" class="layui-btn layui-btn-primary layui-btn-xs" lay-event="down" >下架</button>'
                            }
                        }
                        return html;
                    }
                }
            ]]
        });

        // 获取查询数据
        function getSearchVal() {
            var val = {
                page: currPage,
                limit: limit,
                reviewStatus:  $('select[name=reviewStatus]').val(),
                annexExpiredStatus: $('select[name=annexExpiredStatus]').val(),
                shelfStatus: $('select[name=shelfStatus]').val(),
                productName: $('input[name=productName]').val(),
                supplierName: $('input[name=supplierName]').val(),
                categoryId: $('input[name=categoryId]').val()
            }
            sessionStorage.setItem('xi-can-management-productMSearch', JSON.stringify(val))
        }

        //查询
        form.on('submit(searchBth)', function (data) {
            canteenIdSet = [];
            canteenIdSetList = [];

            let _data = data.field,
				param = _data;
			selectTable.reload({
				page:{curr:1},
				where: param
			})
        })
		
		//状态 0关闭 1开启
		form.on('switch(statusDemo)', function (obj) {
			var state = obj.elem.checked ? 1 : 0;
			var data = {
				productId: obj.value,
			}
			http.post(state==1?'admin/product/public/status/open':'admin/product/public/status/close', data,function (res) {
				if(res.code=='200'){
					// layer.msg('操作成功！');
				}else{
					layer.msg(res.msg);
					selectTable.reload({
						page:{curr:1}
					})
				}
			})
		});

        table.on('tool(selectTable)', function(obj){
            var data = obj.data;
            if(obj.event=='check'){
                // 审核
                location.href = 'productCheck.html?id=' + data.productId
                // $('#my_iframe').attr('src', 'productCheck.html?id=' + data.productId)
                // $('.maincontainer').hide()
                // $('#my_iframe').show()
            }else if(obj.event=='up'){
                // 上架
                location.href = 'productShelf.html?id=' + data.productId + '&type=1'
                // $('#my_iframe').attr('src', 'productShelf.html?id=' + data.productId + '&type=1')
                // $('.maincontainer').hide()
                // $('#my_iframe').show()
            }else if(obj.event=='down'){
                // 下架
                location.href = 'productShelf.html?id=' + data.productId + '&type=2'
                // $('#my_iframe').attr('src', 'productShelf.html?id=' + data.productId + '&type=2')
                // $('.maincontainer').hide()
                // $('#my_iframe').show()

            }else if(obj.event == 'imgclick'){
                http.photos('<div style="text-align:center;width:450px;height:450px;overflow:hidden;"><img src="' + TUrl+data.mainImage + '" style="width:100%;height:100%;object-fit: contain"/></div>')
            }else if(obj.event == 'detail'){
                location.href = "productDetail.html?id=" + data.productId
                // $('#my_iframe').attr('src', 'productDetail.html?id=' + data.productId + '&type=1')
                // $('.maincontainer').hide()
                // $('#my_iframe').show()
            }
        })

        table.on('checkbox(selectTable)', function(obj){
            if(obj.type == 'all') { // 全选
                if(obj.checked){
                    excelList.forEach(function(value, key) {
                        if(value.reviewStatus != 0){ // 不可选
                            $(".layui-table tr[data-index="+key+"] input[type='checkbox']").prop('checked',false);
                            $(".layui-table tr[data-index="+key+"] input[type='checkbox']").next().removeClass('layui-form-checked')
                        }else{
                            canteenIdSetList.push(value)
                            canteenIdSet.push(value.productId);
                        }
                    })
                }else{
                    for(var i=0;i<canteenIdSet.length;i++){
                        for(var j=0;j<excelList.length;j++){
                            if(canteenIdSet[i]==excelList[j].productId){
                                canteenIdSetList.splice(i,1)
                                canteenIdSet.splice(i,1);
                            }
                        }
                    }
                }
            }else{
                if(obj.checked==true){
                    if(obj.type=='one'){
                        canteenIdSetList.push(obj.data)
                        canteenIdSet.push(obj.data.productId);
                    }else{
                        for(var i=0;i<excelList.length;i++){
                            canteenIdSetList.push(excelList[i])
                            canteenIdSet.push(excelList[i].productId);
                        }
                    }
                }else{
                    if(obj.type=='one'){
                        for(var i=0;i<canteenIdSet.length;i++){
                            if(canteenIdSet[i]==obj.data.productId){
                                canteenIdSetList.splice(i,1)
                                canteenIdSet.splice(i,1);
                            }
                        }
                    }else{
                        for(var i=0;i<canteenIdSet.length;i++){
                            for(var j=0;j<excelList.length;j++){
                                if(canteenIdSet[i]==excelList[j].productId){
                                    canteenIdSetList.splice(i,1)
                                    canteenIdSet.splice(i,1);
                                }
                            }
                        }
                    }
                }
            }

        });
        // 回显选中的商品
        function canteenFun(){
            canteenTable = http.table1({
                elem: '#canteenTable',
                id: 'canteenTable',
                cols: [[
                    {title:'序号',type:'numbers'},
                    {field:'mainImage', title: '商品图片', align : 'center',
                        templet: function (d) {
                            return '<div ><img src="'+TUrl+d.mainImage+'" alt="" width="50px" height="30px"></div>'
                        }
                    }
                    ,{field:'productName', title: '商品名称', align: 'center', width: 170}
                    ,{field:'supplierName', title: '供应商名称', align: 'center'}
                    ,{field:'categoryName', title: '商品类别', align: 'center',width: 120,}
                    ,{field:'unitName', title: '单位', align: 'center'}
                    ,{field:'priceRange', title: '价格', align: 'center'}
                    ,{field:'sortNumber', title: '排序', align: 'center'}
                    ,{field:'shelfStatus', title: '商品状态', align: 'center',
                        templet: function (d) {
                            return d.shelfStatus==1?'上架':'下架';
                        }
                    }
                    ,{field:'reviewStatus', title: '审核状态', align: 'center',
                        templet: function (d) {
                            return d.reviewStatus==0?'<span style="color:#0066FF">待审核</span>':(d.reviewStatus==1?'<span style="color:#000000">审核通过</span>':'<span style="color: #FF0000">审核不通过</span>');
                        }
                    }
                    ,{field:'reportDueTime', title: '检测报告到期时间', align: 'center',width: 170,
                        templet: function (d) {
                            return d.reportDueTime?d.reportDueTime.split(' ')[0]:'';
                        }
                    }
                    ,{field:'publicStatus', title: '是否公示', align: 'center',
                        templet: function (d) {
                            return d.publicStatus==1?'是':'否';
                        }
                    }
                    ,{field:'', title: '操作', align: 'center',width: 130,
                        templet: function (d) {
                            var html = '';
                            html += '<button type="button" class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del" >删除</button>'
                            return html;
                        }
                    }
                ]],
                limit: canteenIdSetList.length,
                data: canteenIdSetList
            })
            // table操作
            table.on('tool(canteenTable)', function(obj){
                var data = obj.data;
                if(obj.event=='del'){
                    // 删除
                    var index = $(obj.tr).eq(0).data('index')
                    canteenIdSetList.splice(index,1)
                    canteenIdSet.splice(index,1)
                    canteenFun()
                }
            })
        }
        table.on('toolbar(selectTable)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id); //获取选中行状态
            var data = checkStatus.data; //获取选中行数据
            if(obj.event == 'change'){ // 批量审核同意
                if (canteenIdSet.length == 0) {
                    layer.msg("请勾选需要批量审核同意的商品");
                    return;
                }
                http.myOpen({
                    title:'批量审核同意',
                    content: $('#tableForm'),
                    area:['900px','500px'],
                    btn:['确定','取消'],
                    success: function(){
                        canteenFun()
                    },
                    btn1:function(index, layero){
                        if(canteenIdSet.length == 0){
                            layer.msg("请勾选需要批量审核同意的商品");
                            return;
                        }
                        http.postJSON('admin/product/review/agree/batch', JSON.stringify(canteenIdSet),function(res){
                            if(res.code == 200){
                                canteenIdSet = [] // 商品id集合
                                canteenIdSetList = [] // 选中商品
                                layer.msg('操作成功')
                                layer.close(index)
                                table.reload('selectTable');
                            }else{
                                layer.msg(res.msg)
                            }
                        })
                    }
                })
            }else if(obj.event == 'export'){ // 导出
				var data = excelList; 
				if (data.length == 0) {
					layer.msg('当前页没有可导出的数据');
					return;
                }
                var param = {
                    page: currPage,
                    limit: 10,
                    authentication: localStorage.getItem('xi-can-management-authentication'),
                    reviewStatus:  $('select[name=reviewStatus]').val(),
                    annexExpiredStatus: $('select[name=annexExpiredStatus]').val(),
                    shelfStatus: $('select[name=shelfStatus]').val(),
                    supplierName: $('input[name=supplierName]').val(),
                    productName: $('input[name=productName]').val(),
                    // productCategoryName: $('input[name=productCategoryName]').val(),
                    categoryId: $('input[name=categoryId]').val()
                }
                if (param) {  
                    let paramsArray = [];  
                    //encodeURIComponent  
                    Object.keys(param).forEach(key => paramsArray.push(key + '=' + param[key]))  
                    window.open(TUrl+"admin/product/export?"+paramsArray.join('&'))
                }
			}
        })

    })

</script>
</html>